package com.ad.aidai.fragments.order.order_push;

import android.content.Context;
import android.content.SharedPreferences;
import android.view.ViewGroup;

import com.ad.aidai.bean.Order;
import com.ad.aidai.common.ADApp;
import com.ad.aidai.network.NetWork;
import com.ad.aidai.network.StatusCodeFromNet;
import com.ad.aidai.network.result.GetOrderListFromNet;
import com.ad.aidai.viewholder.OrderThreeLineViewHolder;
import com.ad.aidai.viewholder.OrderViewHolder;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static android.content.Context.MODE_PRIVATE;

/**
 * OrderPushPresenter
 * <p>
 * Created by Yusxon on 17/1/13.
 */

public class OrderPushPresenter implements OrderPushContract.Presenter {

    private Context mContext;
    private OrderPushContract.View mView;
    /**
     * view的设配器
     */
    private RecyclerArrayAdapter<Order> orderAdapter;

    /**
     * 当前是否在刷新
     */
    private boolean isRefreshing = false;

    /**
     * 是否有设置推送,默认为false
     */
    private boolean isSetPush = false;

    private boolean isAutoPush = false;

    private SharedPreferences push;

    public OrderPushPresenter(Context context, OrderPushContract.View view) {
        this.mContext = context;
        this.mView = view;
        mView.setPresenter(this);
        push = mContext.getSharedPreferences("AIDAI", MODE_PRIVATE);
        orderAdapter = new RecyclerArrayAdapter<Order>(mContext) {

            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                if (viewType == Order.STATUS_NO_RECIEVE) {
                    return new OrderThreeLineViewHolder(parent);
                }
                return new OrderViewHolder(parent);
            }

            @Override
            public int getViewType(int position) {
                return mObjects.get(position).getOrderStatus();
            }
        };
        orderAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                ADApp.setOrder(orderAdapter.getItem(position));
                mView.intoItem();
            }
        });
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unSubscribe() {
        mContext = null;
        mView = null;
    }

    @Override
    public RecyclerArrayAdapter<Order> getAdapter() {
        return orderAdapter;
    }

    @Override
    public void refresh() {
        refreshOrders();
    }

    @Override
    public boolean isSetPush() {
        return isSetPush;
    }

    @Override
    public void pushSettingChange() {
        isSetPush = mContext.getSharedPreferences("AIDAI", MODE_PRIVATE).getBoolean("ISSETPUSH", false);
        mView.isSetPush(isSetPush);
        if (isSetPush) {
            autoRefresh();
        }
    }

    /**
     * 推送(自动刷新)
     */
    private void autoRefresh() {
        if (isAutoPush) {
            return;
        }
        Observable
                .create(new Observable.OnSubscribe<List<Order>>() {
                    @Override
                    public void call(Subscriber<? super List<Order>> subscriber) {
                        while (isSetPush) {
                            isAutoPush = true;
                            try {
                                if (!isRefreshing) {
                                    Logger.t(this.getClass().getSimpleName()).i("推送ing");
                                    refreshOrders();
                                }
                                Long time = push.getLong("pushTimes", 30L);
                                Thread.sleep(time * 1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        subscriber.onCompleted();
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<Order>>() {
                    @Override
                    public void onCompleted() {
                        isAutoPush = false;
                        Logger.t(this.getClass().getSimpleName()).i("取消推送设置");
                    }

                    @Override
                    public void onError(Throwable e) {
                        MobclickAgent.reportError(mContext, e);
                    }

                    @Override
                    public void onNext(List<Order> o) {
                    }
                });
    }

    private Map<String, String> getMaps() {
        Map<String, String> maps = new HashMap<>();
        maps.put("userLongtitude", String.valueOf(ADApp.getUserLongtitude()));
        maps.put("userLatitude", String.valueOf(ADApp.getUserLatitude()));
        maps.put("userId", String.valueOf(ADApp.getUser().getUserId()));

        return maps;
    }

    /**
     * 刷新订单
     */
    private void refreshOrders() {
        if (!isRefreshing) {
            isRefreshing = true;
            NetWork.getOrderOperationApi()
                    .pushOrderList(getMaps())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<GetOrderListFromNet>() {
                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable e) {
                            MobclickAgent.reportError(mContext, e);
                            Logger.t("OrderPushPresenter").e(e.getMessage());
                            //                            mView.toast("刷新失败");
                            isRefreshing = false;
                            orderAdapter.add(null);
                        }

                        @Override
                        public void onNext(GetOrderListFromNet result) {
                            isRefreshing = false;
                            if (result.getCode() == StatusCodeFromNet.CODE_SUCCESS) {
                                Logger.t("OrderPushPresenter").i(result.toString());
                                List<Order> orders = result.getData();
                                orderAdapter.clear();
                                orderAdapter.addAll(orders);
                            } else {
                                //                                mView.toast("刷新失败");
                                orderAdapter.add(null);
                                Logger.t("OrderPushPresenter").e(result.toString());
                            }
                        }
                    });
        }
    }

    @Override
    public void orderStatusChange(Order order) {
        if (isSetPush && orderAdapter != null && orderAdapter.getCount() > 0) {
            int position = 0;
            for (Order oldOrder : orderAdapter.getAllData()) {
                if (oldOrder.getOrderId() == order.getOrderId()) {
                    orderAdapter.remove(position);
                    if(order.getOrderStatus() != Order.STATUS_CANCEL) {
                        orderAdapter.insert(order, position);
                    }
                    break;
                }
                position++;
            }
        }
    }
}
